package demo;

/**
 * 字符串转换整数 (atoi)
 */
public class Solution40 {
	public int myAtoi(String s) {
		char[] str = s.toCharArray();
		int length = str.length;
		int idx = 0;
		while (idx < length && str[idx] == ' ') {
			idx++;
		}
		if (idx == length) {
			return 0;
		}
		boolean negative = false;
		if (str[idx] == '-') {
			negative = true;
			idx++;
		}
		if (str[idx] == '+') {
			idx++;
		}
		if (!Character.isDigit(str[idx])) {
			return 0;
		}
		int result = 0;
		while (idx < length && Character.isDigit(str[idx])) {
			int digit = str[idx] - '0';
			if (result > (Integer.MAX_VALUE - digit) / 10 ) {
				return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
			}
			result = result * 10 + digit;
			idx++;
		}

		return negative ? -result : result;
	}
}
